<template>
  <div class="container">
    <div class="operate-area">
      <el-upload
          ref="upload"
          action="#"
          :file-list="fileList"
          :on-change="handleFileChange"
          :show-file-list="false"
          :auto-upload="false"
          multiple>
        <el-button class="upload-btn" size="small">批量选择文件</el-button>
      </el-upload>
      <el-button type="success" size="small" style="margin-left: 5px" @click="handleSubmitFile">上传至服务器</el-button>
      <el-button type="primary" size="small" style="margin-left: 5px" @click="startBatchSegmentation">开始批量分割</el-button>
      <el-button type="warning" size="small" style="margin-left: 5px" @click="resetFileList">重置文件列表</el-button>
      <el-button type="info" size="small" style="margin-left: 5px" @click="exportResult">导出分割结果</el-button>
    </div>
    <div class="result-area">
      <el-table
          class="result-table"
          stripe
          :header-cell-style="{background:'#eef1f6', color:'#606266'}"
          :data="tableData"
          style="width: 100%">
        <el-table-column
            prop="rawImage"
            label="原图片">
          <template slot-scope="scope">
            <img :src="scope.row.rawImage" alt="" style="width: 50%;height: 50%"/>
          </template>
        </el-table-column>
        <el-table-column
            prop="resultImage"
            label="分割结果">
          <template slot-scope="scope">
            <el-image :src="scope.row.resultImage" style="width: 50%;height: 50%">
              <div slot="error" class="image-slot">
                暂无
              </div>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column
            prop="areaRatio"
            label="面积占比">
          <template slot-scope="scope">
            <div class="areaRatio">{{scope.row.areaRatio + '%'}}</div>
          </template>
        </el-table-column>
        <el-table-column
            prop="status"
            label="状态">
          <template slot-scope="scope">
            <div class="status-icon" :style="scope.row.status === '已分割' ? {backgroundColor: '#67C23A'} : {backgroundColor: 'rgb(153, 153, 153)'}"></div>
            <div class="status-text" :style="scope.row.status === '已分割' ? {color: '#67C23A'} : {color: 'rgb(153, 153, 153)'}">{{scope.row.status}}</div>
          </template>
        </el-table-column>
        <el-table-column
            label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="deleteTargetFilename(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import {createSegmentationTable, segmentation} from "@/api/segmentation";
import axios from "axios";

export default {
  name: 'BatchSegmentation',
  data() {
    return {
      tableData: [
        {
          rawImage: 'https://fundusdetection.oss-cn-beijing.aliyuncs.com/0000.png',
          resultImage: 'https://fundusdetection.oss-cn-beijing.aliyuncs.com/pred_0000.png',
          areaRatio: 11.102,
          status: '等待分割'
        }
      ],
      fileList: [],
      filenameList: [],
      areaRatioList: []
    }
  },
  methods: {
    handleFileChange(file,fileList) {
      this.fileList = fileList
    },
    handleSubmitFile() {
      let loading = this.$loading({
        lock: true,
        text: '文件上传中，请稍后...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      this.tableData = []

      let formData = new FormData()
      // 传文件数组 循环append
      for ( let i = 0 ; i < this.fileList.length ; i ++ ) {
        formData.append('files', this.fileList[i].raw)
      }

      // 上传到服务器
      axios.post('http://yiyuy.mynatapp.cc/model/uploadBatchImage', formData, {
        headers: { "Content-Type": "multipart/form-data" }
      }).then(response => {
        response = response.data;
        for ( let i = 0 ; i < response.data.length ; i ++ ) {
          let obj = {
            rawImage: 'data:image/png;base64,' + response.data[i].base64,
            resultImage: '',
            areaRatio: 0,
            status: '等待分割',
          }
          this.filenameList.push(response.data[i].filename)
          this.tableData.push(obj)
          console.log(this.tableData)
        }
        loading.close();
        this.$message.success("文件上传成功！");
      }).catch(error => {
        this.$message.error("文件上传失败！");
        console.error(error);
      });
    },
    resetFileList() {
      this.tableData =  [
        {
          rawImage: 'https://fundusdetection.oss-cn-beijing.aliyuncs.com/0000.png',
          resultImage: 'https://fundusdetection.oss-cn-beijing.aliyuncs.com/pred_0000.png',
          areaRatio: 11.102,
          status: '等待分割'
        }
      ]
      this.$refs.upload.clearFiles();
      this.filenameList = []
      this.$message.success('重置成功')
    },
    startBatchSegmentation() {
      if (this.filenameList.length <= 0 ) {
        this.$message.warning('请先上传图片')
        return;
      }

      let loading = this.$loading({
        lock: true,
        text: '图像批量分割中，请稍后...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      for ( let i = 0 ; i < this.filenameList.length ; i ++ ) {
        let formData = {
          filename : this.filenameList[i]
        }
        segmentation(formData).then(response => {
          this.tableData[i].resultImage = 'data:image/png;base64,' + response.data.base64
          this.tableData[i].areaRatio = response.data.areaRatio
          this.tableData[i].status = '已分割'
          this.areaRatioList.push(response.data.areaRatio)
          if ( i === this.filenameList.length - 1 ) {
            this.$message.success('图像批量分割成功')
            loading.close();
          }
        })
      }

    },
    deleteTargetFilename(row) {
      this.filenameList.splice(this.filenameList.indexOf(row.rawImage), 1)
      this.tableData.splice(this.tableData.indexOf(row), 1)
      this.$message.success('删除成功')
    },
    exportResult() {
      if ( this.filenameList.length <= 0 ) {
        this.$message.warning('请先上传图片')
        return;
      }

      let form = {
        filenameList: this.filenameList,
        areaRatioList: this.areaRatioList
      }

      createSegmentationTable(form).then(res => {
        // 创建一个隐藏的<a>元素
        let link = document.createElement('a');
        link.style.display = 'none';
        document.body.appendChild(link);

        // 通过 Flask 的路由来获取文件路径
        link.href = 'http://yiyuy.mynatapp.cc/model/getExportResult';

        // 模拟点击事件来触发文件下载
        link.click();

        // 移除创建的<a>元素
        document.body.removeChild(link);
      })
    }
  }
}
</script>

<style lang="less" scoped>
@keyframes MoveIn {
  0% {
    opacity: 0;
    transform: translateY(12px);
  }

  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

.container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  animation: MoveIn 0.5s ease-in-out;

  .operate-area {
    margin-top: 15px;
    display: flex;

    .upload-btn {
      background-color: rgb(70, 108, 245);
      color: #ffffff;
    }
  }
  
  .result-area {
    flex: 1;
    margin-top: 5px;
    overflow-y: auto;

    .areaRatio {
      font-weight: 700;
      color: #409EFF;
    }

    .result-table {
      height: 100%;

      .status-icon{
        width: 10px;
        height: 10px;
        border-radius: 50%;
        display: inline-block;
        margin-right: 5px;
      }

      .status-text {
        display: inline-block;
        color: rgb(153, 153, 153);
        font-size: 12px;
      }
    }
  }
}
</style>